package com.zhong.gang.applib.utils.permission;

import android.app.Activity;
import android.widget.Toast;

import androidx.fragment.app.Fragment;

import com.yanzhenjie.permission.*;

import java.util.List;
import java.util.Locale;


public abstract class PermissionBase {

    public Activity act;
    public Fragment fragment;
    PermissionListener permissionListener;
    public PermissionBase(Activity act, PermissionListener permissionListener) {
        this.act = act;
        this.permissionListener = permissionListener;
        requestPermission(getPermissCode(),getPermissions());
    }

    public PermissionBase(Fragment fragment, PermissionListener permissionListener) {
        this.fragment = fragment;
        this.permissionListener = permissionListener;
        requestPermission(getPermissCode(),getPermissions());
    }

    /**
     * 申请SD卡权限，单个的。
     */
    public void requestPermission(int requestCode, String... permissions) {
        Request request = null;
        if (act != null)
        request = AndPermission.with(act);
        else if (fragment != null)
            request = AndPermission.with(fragment);
        if (request == null)
            return;
        request.requestCode(requestCode)
                .permission(permissions)
                .callback(permissionListener)
                .rationale(new RationaleListener() {
                    @Override
                    public void showRequestPermissionRationale(int requestCode, Rationale rationale) {
                        // 这里的对话框可以自定义，只要调用rationale.resume()就可以继续申请。
                        AndPermission.rationaleDialog(act!=null?act:fragment.getContext(), rationale).show();
                    }
                }).start();
    }
    public static void showNoPermissionDialog(final Activity act, int requestCode, List<String> deniedPermissions) {
        Toast.makeText(act, String.format(Locale.CHINA,"权限错误"), Toast.LENGTH_LONG).show();
        // 用户否勾选了不再提示并且拒绝了权限，那么提示用户到设置中授权。
        if (AndPermission.hasAlwaysDeniedPermission(act, deniedPermissions)) {
            // 第一种：用默认的提示语。
            AndPermission.defaultSettingDialog(act, requestCode).show();
        }
    }
    public abstract String[] getPermissions();
    public abstract int getPermissCode();
}
